<template>
	<div class="pet-refresh">
		<scroll-view 
			scroll-anchoring
			class="swiper-item-content"
			:refresher-threshold="refresherThreshold"
			refresher-background="#000000"
			:scroll-y="scrollY" 
			:refresher-enabled="refresh" 
			:refresher-triggered="refresStatus" 			
			@refresherrefresh="$u.throttle(onRefresh,500)" 
			@scrolltolower="$u.throttle(onLoading,500)"
			@scroll="scroll"
		>
			<slot></slot>
			<div class="loadmore" v-if="refresh && showLoadmore">
				<u-loadmore v-if="page" @loadmore="onLoadmore" :status="page.status" />
			</div>
			<div v-if="safeBottom" class="safeBottom"></div>
		</scroll-view>
	</div>
</template>

<script>
	export default {
		props: {
			//下拉刷新阈值
			refresherThreshold: {
				type: Number,
				default: 120
			},
			//是否可以下啦刷新
			refresh: {
				type: Boolean,
				default: true
			},
			//y轴是否可以
			scrollY: {
				type: Boolean,
				default: true
			},
			//是否有安全距离
			safeBottom: {
				type: Boolean,
				default: true
			},
			//每个刷新组件的名字，一个页面可能会有多个刷新组件，例如三个分页的那种格式
			pageName: {
				type: String,
				default: 'page'
			},
			//是否自动刷新
			automaticRefresh: {
				type: Boolean,
				default: true
			},
			//是否调用自定义刷新函数
			customRefresh: {
				type: Boolean,
				default: false
			}
		},
		data() {
			return {
				//刷新状态
				refresStatus: false,
				page: null
			};
		},
		mounted() {
			//获取父组件的分页组件
			this.page = this.getPage();
		},
		methods: {
			//上啦加载
			onLoadmore(){
				this.onLoading();
			},
			//下啦刷新
			async onRefresh(){
				this.refresStatus = true;
				if(this.page.onRefresh) await this.page.onRefresh();
				setTimeout(() => {
					this.refresStatus = false;
				},300)
			},
			//上啦加载
			async onLoading(){
				if(!this.refresh) return;
				if(this.page.onLoadmore)
				await this.page.onLoadmore();
			},
			//往父组件找是否有该变量
			getPage(){
				var that = this;
				//只找10层
				for(let i = 0;i < 10;i++){
					if(that[this.pageName])return that[this.pageName];
					that = that.$parent;
					if(!that) return {};
				}
				return {};
			},
			scroll(e){
				this.$emit('scroll' , e)
			}
		},
		computed: {
			showLoadmore(){
				if(this.page && (this.page.status === 'nomore' || this.page.status === undefined)) return false;
				else return true;
			}
		}
	}
</script>

<style lang="scss">
	.pet-refresh{
		height: 100%;
		width: 100%;
		position: relative;
		.swiper-item-content{
			position: absolute;
			top: 0;
			bottom: 0;
			height: 100%;
			width: 100%;
			.loadmore{
				padding: 30rpx 0;
			}
			.safeBottom{
				// height: env(safe-area-inset-bottom);
				height: 88rpx;
				width: 100vw;
			}
		}
	}
</style>
